var express = require('express')
var multipart = require('connect-multiparty')
var multipartMiddleware = multipart()
var mysql = require('../dataBase')
// 定义路由
var app = express.Router()
// 获取所有的后台用户
app.post('/userList', multipartMiddleware, (req, res) => {
  let sql = `SELECT id,account,name,phone,sex,createTime,jurisdiction  from userList `
  mysql.query(sql, (err, result) => {
  
    if (result && result[0]) {
      res.send({ state: 'OK', data: result })
    } else {
      res.send({ state: 'error', data: '暂无数据或服务器无响应！' })
    }
  })
})
// 修改后台用户信息
app.post('/editUser', multipartMiddleware, (req, res) => {
  let $id = req.body.id
  let $name = req.body.name
  let $account = req.body.account
  let $phone = req.body.phone
  let $jur = req.body.jur
  let $sex = req.body.sex
  let sql = `update userList set name='${$name}',account='${$account}',jurisdiction='${$jur}',phone='${$phone}',sex='${$sex}' where id=${$id}`
  mysql.query(sql, (err, result) => {
    if (!err) {
      res.send({ state: 'OK', data: '修改成功' })
    } else {
      res.send({ state: 'error', data: '修改失败，服务器无响应！' })
    }
  })
})
// 删除数据
app.post('/delete', multipartMiddleware, (req, res) => {
  let $id = req.body.id
  let sql = `delete from userList where id=${$id}`
  mysql.query(sql, (err, result) => {
    if (!err) {
      res.send({ state: 'OK', data: '删除成功' })
    } else {
      res.send({ state: 'error', data: '删除失败，服务器无响应！' })
    }
  })
})
// 获取单条数据
app.post('/getInfo', multipartMiddleware, (req, res) => {
  let $id = req.body.id
  let sql = `SELECT id,account,name,phone,sex,createTime,jurisdiction  from userList  where id=${$id}`
  mysql.query(sql, (err, result) => {
    if (result[0]) {
      let account = result[0].account
      let pass = result[0].password
      let name = result[0].name
      let phone = result[0].phone
      let sex = result[0].sex
      let jur = result[0].jurisdiction
      let id = result[0].id
      res.send({
        state: 'OK',
        data: {
          u_id: id,
          u_name: name,
          u_account: account,
          u_phone: phone,
          u_sex: sex,
          u_jurisdiction: jur,
        },
      })
    } else {
      res.send({ state: 'error', data: '获取失败，服务器无响应！' })
    }
  })
})
module.exports = app
